// 导入模块
import { userStore } from '@/store/userStore'
import Request from 'luch-request'

// 实例化网络请求
const request = new Request({
  // 接口基地址
  baseURL: 'https://consult-api.itheima.net',
  // 设置加载中弹窗
  custom: {
    loading: true,
  },
})
request.interceptors.request.use(
  (config) => {
    if (config.custom?.loading) {
      uni.showLoading({
        title: '加载中',
      })
    }
    const store = userStore()
    if (store.token) {
      config.header!.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截
request.interceptors.response.use(
  (response) => {
    uni.hideLoading()
    if (response.data.code !== 10000) {
      uni.showToast({
        title: response.data.message,
        icon: 'none',
      })
      return Promise.reject(response.data)
    }
    return response.data?.data
  },
  (error) => {
    uni.hideLoading()
    if (error.data.code === 401) {
      uni.showToast({
        title: error.data.message,
        icon: 'none',
      })
      const store = userStore()
      store.clearToken()
      uni.redirectTo({
        url: '/pages/login/login',
      })
    }
    return Promise.reject(error)
  }
)
// 导出配置好的模网络模块
export { request }
